package com.yanqu.road.server.gameplayer.module.activity.winterLove;

import com.yanqu.road.entity.DataStatus;
import com.yanqu.road.entity.activity.ActivityDisperseGoldInfo;
import com.yanqu.road.entity.activity.ActivityDisperseGoldResult;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.winterLove.WinterLoveBagItem;
import com.yanqu.road.entity.activity.winterLove.WinterLoveMapAnimal;
import com.yanqu.road.entity.activity.winterLove.WinterLoveUserData;
import com.yanqu.road.entity.activity.winterLove.WinterLoveMapItem;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveComb;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveConfig;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveItem;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.eDecorationType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogWinterLoveConvertReward;
import com.yanqu.road.entity.log.LogWinterLoveDig;
import com.yanqu.road.entity.log.LogWinterLovePickUpItem;
import com.yanqu.road.logic.bussiness.activity.WinterLoveBusiness;
import com.yanqu.road.pb.activity.WinterLoveProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.winterLove.WinterLoveMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.pb.WinterLovePb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class WinterLoveModule extends GeneralModule {

    private WinterLoveUserData userData;

    public WinterLoveModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        ActivityInfo activityInfo = WinterLoveMgr.getActivityInfo();
        if (ActivityMgr.activityInShowTime(activityInfo)) {
            userData = WinterLoveBusiness.getWinterLoveUserData(activityInfo.getActivityId(), player.getUserId());
            if (null == userData) {
                initUserData();
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (null != userData) {
            if (userData.isInsertOption()) {
                WinterLoveBusiness.addWinterLoveUserData(userData);
            } else if (userData.isUpdateOption()) {
                WinterLoveBusiness.updateWinterLoveUserData(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        syncWinterLoveConfig();
        syncUserData();
    }

    /**
     * 冬季恋歌散财
     */
    public ActivityDisperseGoldResult disperseGold(ActivityInfo activityInfo, String manifesto) {
        WinterLoveConfig winterLoveConfig = WinterLoveMgr.getWinterLoveConfig();
        ActivityDisperseGoldResult result = new ActivityDisperseGoldResult();
        if (activityInfo.getActivityId() != winterLoveConfig.getActivityInfo().getActivityId()) {
            result.setRet(GameErrorCode.E_WINTER_LOVE_ACTIVITY_NO_OPEN);
            return result;
        }
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            result.setRet(GameErrorCode.E_WINTER_LOVE_ACTIVITY_NO_OPEN);
            return result;
        }
        if (userData.getDisperseTimes() + 1 > WinterLoveMgr.getDisperseMaxTime()) {
            result.setRet(GameErrorCode.E_WINTER_LOVE_DISPERSE_GOLD_TIMES_MAX);
            return result;
        }
        //判断积分和美女祝福是否满足
        if (userData.getScore() < winterLoveConfig.getDisperseGoldScoreLimit()) {
            result.setRet(GameErrorCode.E_WINTER_LOVE_DISPERSE_GOLD_SCORE_NO_ENOUGH);
            return result;
        }
        if (userData.getBlessing() < WinterLoveMgr.getNowDisperseBlessLimit(userData.getDisperseTimes())) {
            result.setRet(GameErrorCode.E_WINTER_LOVE_DISPERSE_GOLD_BLESS_NO_ENOUGH);
            return result;
        }

        List<Integer> decorationIdList = player.getModule(DecorationModule.class).getDecorationIdList(eDecorationType.HonoraryTitle.getValue());
        ActivityDisperseGoldInfo goldInfo = new ActivityDisperseGoldInfo();
        goldInfo.setActivityId(activityInfo.getActivityId());
        goldInfo.setType(activityInfo.getType());
        goldInfo.setUserId(player.getUserId());
        goldInfo.setManifesto(manifesto);
        goldInfo.setBeginTime(System.currentTimeMillis());
        goldInfo.setHonoraryTitles(StringUtils.listToString(decorationIdList, ","));

        if (NormalActivityMgr.hasConditionType(activityInfo.getActivityId(), eGamePlayerEventType.WinterLoveRank.getValue())) {
            goldInfo.setServerList(activityInfo.getServerIdList());
        } else {
            List<Long> serverList = new ArrayList<>();
            serverList.add(GameServer.getInstance().getServerId());
            goldInfo.setServerList(serverList);
        }
        goldInfo.setUserBaseInfo(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId()));
        result.setRet(0);
        result.setGoldInfo(goldInfo);
        userData.setDisperseTimes(userData.getDisperseTimes() + 1);
        syncUserData();

        return result;

    }

    /**
     * 装饰物兑换奖励
     */
    public int convertReward(int combId) {
        WinterLoveConfig config = WinterLoveMgr.getWinterLoveConfig();
        WinterLoveComb comb = new WinterLoveComb();
        for (WinterLoveComb winterLoveComb : config.getWinterLoveCombList()) {
            if (winterLoveComb.getCellID() == combId) {
                comb = winterLoveComb;
                break;
            }
        }
        if (comb.getCombination() == null) {
            return GameErrorCode.E_WINTER_LOVE_COMB_NO_EXIXT;
        }
        WinterLoveProto.cashRewardRespMsg.Builder builder = WinterLoveProto.cashRewardRespMsg.newBuilder();
        //判断物品栏中是否有所有物品
        if (checkCombEnough(comb)) {
            //扣除个人数据里的装饰品
            deductDecoration(comb);
            Property rewardProperty = PropertyHelper.parseStringToProperty(comb.getRewards());
            //获得奖励之后拿出美女祝福数
            int convertBlessNum = rewardProperty.getCountByGoodsId(config.getBlessItemId()).intValue();
            userData.setBlessing(userData.getBlessing() + convertBlessNum);
            BigDecimal bigDecimal = BigDecimal.valueOf(userData.getBlessing());
            player.notifyListener(eGamePlayerEventType.WinterLoveBlessCount.getValue(), bigDecimal);
            //移除美女祝福物品,加入背包
            rewardProperty.removeProperty(config.getBlessItemId());
            player.getModule(CurrencyModule.class).addCurrency(rewardProperty, eLogMoneyType.WinterLoveActivity, eLogMoneyType.WinterLoveCashReward);

            for (WinterLoveBagItem bagItem : userData.getDecoration()) {
                WinterLoveProto.UserItemData.Builder itemBuilder = WinterLoveProto.UserItemData.newBuilder();
                itemBuilder.setItemId(bagItem.getDecorationId());
                itemBuilder.setItemNum(bagItem.getDecorationNum());
                builder.addUserItem(itemBuilder);
            }
            builder.setReward(comb.getRewards());
            builder.setRet(0);
            LogWinterLoveConvertReward logWinterLoveConvertReward = new LogWinterLoveConvertReward(player.getUserId(), config.getActivityInfo().getActivityId(), combId, comb.getRewards(), new Date());
            LogMgr.addWinterLoveConvertReward(logWinterLoveConvertReward);

            player.sendPacket(Protocol.U_WINTER_LOVE_CASH_REWARD_RESULT, builder);
            syncPlayerData();
            return 0;
        } else {
            return GameErrorCode.E_WINTER_LOVE_COMB_NO_COMPLETE;
        }

    }

    /**
     * 扣除组合装饰物
     */
    private void deductDecoration(WinterLoveComb comb) {
        for (int needItemId : comb.getCombination()) {
            WinterLoveBagItem haveItem = getBagItemById(needItemId);
            if (haveItem != null) {
                haveItem.setDecorationNum(haveItem.getDecorationNum() - 1);
            }
        }
    }

    /**
     * 查看该组合是否完成
     */
    private boolean checkCombEnough(WinterLoveComb comb) {
        for (int needItemId : comb.getCombination()) {
            WinterLoveBagItem haveItem = getBagItemById(needItemId);
            if (haveItem == null) {
                return false;
            }
            if (haveItem.getDecorationNum() < 1) {
                return false;
            }
        }
        return true;
    }

    /**
     * 通过id获取背包中的物品
     */
    private WinterLoveBagItem getBagItemById(int decorationId) {
        for (WinterLoveBagItem haveItem : userData.getDecoration()) {
            if (decorationId == haveItem.getDecorationId()) {
                return haveItem;
            }
        }
        return null;
    }

    /**
     * 获取当前场次狗狗占用格子
     */
    private List<Integer> getDogGridThisLevel(int level) {
        List<Integer> dogOccupyGridList = new ArrayList<>();
        List<WinterLoveMapAnimal> animalList = level == 1 ? userData.getLowAnimalPosition() : userData.getHighAnimalPosition();
        for (WinterLoveMapAnimal winterLoveMapAnimal : animalList) {
            dogOccupyGridList.addAll(getGridsByDirection(winterLoveMapAnimal.getMainDogGrig() % 6, winterLoveMapAnimal.getMainDogGrig() / 6, 3));
        }
        return dogOccupyGridList;
    }

    /**
     * 领取地图物品或者宝箱进背包
     */

    public int itemToBag(int itemNum, int level) {
        WinterLoveConfig config = WinterLoveMgr.getWinterLoveConfig();
        //判断是否解锁高级场
        if (level == 2 && userData.getBlessing() < config.getHighLevelUnlockBlessNum()) {
            return GameErrorCode.E_WINTER_LOVE_HIGH_LEVEL_NO_UNLOCK;
        }
        //取出用户地图上的物品
        List<WinterLoveMapItem> winterLoveMapItemList = level == 1 ? userData.getLowRewardMapData() : userData.getHighRewardMapData();
        List<Integer> mapData = level == 1 ? userData.getLowMapData() : userData.getHighMapData();
        for (WinterLoveMapItem winterLoveMapItem : winterLoveMapItemList) {
            if (winterLoveMapItem.getItemNum() == itemNum) {
                if (winterLoveMapItem.getInBag() == 1) {           //如果进背包了就返回
                    return GameErrorCode.E_WINTER_LOVE_DECORATE_HAS_RECEIVE;
                }
                //还有格子有雪有狗则返回
                for (int i : winterLoveMapItem.getOccupyList()) {
                    if (mapData.get(i) == 0) {
                        return GameErrorCode.E_WINTER_LOVE_SNOW_COVER_ITEM;
                    }
                    if (getDogGridThisLevel(level).contains(i)) {
                        return GameErrorCode.E_WINTER_LOVE_ANIMAL_ON_ITEM;
                    }
                }

                WinterLoveProto.getItemToBagRespMsg.Builder builder = WinterLoveProto.getItemToBagRespMsg.newBuilder();
                String rewardString = "";
                int boxBlessNum = 0;
                //先判断是不是宝箱
                if (winterLoveMapItem.isBoxItem()) {
                    WinterLoveItem boxItem = WinterLoveMgr.getItemById(winterLoveMapItem.getDecorationId(), level);
                    if (boxItem == null) {
                        return GameErrorCode.E_WINTER_LOVE_BOX_ID_ERROR;
                    }
                    //开宝箱，加奖励，如果有美女祝福也得加
                    winterLoveMapItem.setInBag(1);
                    OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(boxItem.getExtraId());
                    Property rewardProperty = openGoodsBagResult.getReward();
                    //获得奖励之后拿出美女祝福数量,存一个String发给客户端
                    boxBlessNum = rewardProperty.getCountByGoodsId(config.getBlessItemId()).intValue();
                    rewardString = PropertyHelper.parsePropertyToString(openGoodsBagResult.getReward());
                    //移除美女祝福物品
                    rewardProperty.removeProperty(config.getBlessItemId());
                    player.getModule(CurrencyModule.class).addCurrency(rewardProperty, eLogMoneyType.WinterLoveActivity, eLogMoneyType.WinterLoveBoxReward);
                    userData.setBlessing(userData.getBlessing() + boxBlessNum);
                    BigDecimal bigDecimal = BigDecimal.valueOf(userData.getBlessing());
                    player.notifyListener(eGamePlayerEventType.WinterLoveBlessCount.getValue(), bigDecimal);

                } else {
                    winterLoveMapItem.setInBag(1);
                    WinterLoveBagItem winterLoveBagItem = getBagItemById(winterLoveMapItem.getDecorationId());
                    if (null == winterLoveBagItem) {
                        return GameErrorCode.E_WINTER_LOVE_DECORATE_HAS_RECEIVE;
                    }
                    int oldNum = winterLoveBagItem.getDecorationNum();
                    winterLoveBagItem.setDecorationNum(oldNum + 1);
                    userData.setOp(DataStatus.Update);
                }
                int turnNum = level == 1 ? userData.getLowTurn() : userData.getHighTurn();
                int blessNum = 0;
                if (isNextTurn(userData, level)) {
                    builder.setNextTurn(true);
                    for (int i = 0; i < 36; i++) {
                        mapData.set(i, 0);
                    }
                    List<Integer> blessNumList = level == 1 ? config.getLowLevelBlessReward() : config.getHighLevelBlessReward();
                    blessNum = blessNumList.get(Math.min(turnNum, blessNumList.size() - 1));
                    userData.setBlessing(userData.getBlessing() + blessNum);
                    //生成低级场或高级场的动物与奖励
                    if (level == 1) {
                        userData.setLowMapData(mapData);
                        userData.setLowTurn(userData.getLowTurn() + 1);
                        userData.setLowRewardMapData(new ArrayList<>());
                        generateReward(userData, 1);
                        userData.setLowAnimalPosition(new ArrayList<>());
                        generateDog(userData, 1);
                    } else {
                        userData.setHighMapData(mapData);
                        userData.setHighTurn(userData.getHighTurn() + 1);
                        userData.setHighRewardMapData(new ArrayList<>());
                        generateReward(userData, 2);
                        userData.setHighAnimalPosition(new ArrayList<>());
                        generateDog(userData, 2);
                    }
                    userData.setBeautyId(WinterLoveMgr.getRandomBeautyId());
                    BigDecimal bigDecimal = BigDecimal.valueOf(userData.getBlessing());
                    player.notifyListener(eGamePlayerEventType.WinterLoveBlessCount.getValue(), bigDecimal);
                    String blessReward = config.getBlessItemId() + "=" + blessNum;
                    builder.setBlessReward(blessReward);
                } else {
                    builder.setNextTurn(false);
                }
                //日志记录
                int gotBlessing = blessNum + boxBlessNum;
                LogWinterLovePickUpItem logWinterLovePickUpItem = new LogWinterLovePickUpItem(player.getUserId(), config.getActivityInfo().getActivityId(), level, turnNum,
                        winterLoveMapItem.getDecorationId(), rewardString, userData.getBlessing() - gotBlessing, gotBlessing, userData.getBlessing(), new Date());
                LogMgr.addLogWinterLovePickUpItem(logWinterLovePickUpItem);
                //发消息回去
                userData.setUpdateOption();
                builder.setReward(rewardString);
                builder.setRet(0);
                builder.setItemNum(winterLoveMapItem.getItemNum());
                builder.setUserData(WinterLovePb.parseWinterLoveUserDataRespMsg(userData));
                player.sendPacket(ClientProtocol.U_WINTER_LOVE_GET_ITEM_RESULT, builder);

                return 0;
            }
        }
        return GameErrorCode.E_WINTER_LOVE_ITEM_NO_EXIXT;
    }

    /**
     * 挖一次雪
     */
    public int digSnow(int gridId, int level) {
        WinterLoveConfig config = WinterLoveMgr.getWinterLoveConfig();
        if (gridId > 35 || gridId < 0) {
            return GameErrorCode.E_WINTER_LOVE_GRID_ERROR;
        }
        //取出对应场次的消耗和奖励
        if (level == 2 && userData.getBlessing() < config.getHighLevelUnlockBlessNum()) {
            return GameErrorCode.E_WINTER_LOVE_HIGH_LEVEL_NO_UNLOCK;
        }
        int consume = level == 1 ? 1 : config.getHighLevelCost();
        String consumeString = config.getShovelItemId() + "=" + consume;
        String rewardString = config.getScoreItemId() + "=";
        int rewardScoreNum = level == 1 ? WinterLoveMgr.getScoreReward() : WinterLoveMgr.getScoreReward() * config.getHighLevelScoreMultiple();         //高级场积分奖励乘一个倍数
        rewardString = rewardString + rewardScoreNum;
        //取出地图信息
        List<Integer> mapList = level == 1 ? userData.getLowMapData() : userData.getHighMapData();

        if (mapList.get(gridId) == 0) {
            //扣一个活动道具
            if (!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(consumeString), eLogMoneyType.WinterLoveActivity, eLogMoneyType.WinterLoveDigSnowConsume)) {
                return GameErrorCode.E_WINTER_LOVE_SHOVEL_NO_ENOUGH;
            }
            mapList.set(gridId, 1);
            if (level == 1) {
                userData.setLowMapData(mapList);
            } else {
                userData.setHighMapData(mapList);
            }
            //加积分,变排行
            player.getModule(CurrencyModule.class).addCurrency(config.getScoreItemId() + "=" + rewardScoreNum, eLogMoneyType.WinterLoveActivity, eLogMoneyType.WinterLoveDigSnowReward);
            userData.setScore(userData.getScore() + rewardScoreNum);
            player.notifyListener(eGamePlayerEventType.WinterLoveRank.getValue(), userData.getScore());
            //日志记录
            List<Integer> logGridList = new ArrayList<>();
            logGridList.add(gridId);
            int turnNum = level == 1 ? userData.getLowTurn() : userData.getHighTurn();
            LogWinterLoveDig logWinterLoveDig = new LogWinterLoveDig(player.getUserId(), config.getActivityInfo().getActivityId(),
                    level, turnNum, 0, logGridList, userData.getScore() - rewardScoreNum, rewardScoreNum, userData.getScore(), new Date());
            LogMgr.addLogWinterLoveDig(logWinterLoveDig);

            //返回挖雪消息
            WinterLoveProto.DigSnowRespMsg.Builder respMsg = WinterLoveProto.DigSnowRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setSnowGridNum(gridId);
            respMsg.setUserData(WinterLovePb.parseWinterLoveUserDataRespMsg(userData));
            respMsg.setScoreReward(rewardString);
            player.sendPacket(Protocol.U_WINTER_LOVE_DIG_RESULT, respMsg);
            return 0;
        }
        return GameErrorCode.E_WINTER_LOVE_GRID_HAS_DIG;
    }


    /**
     * 赶走动物
     */
    public int kickAnimal(int animalNum, int level) {
        WinterLoveConfig config = WinterLoveMgr.getWinterLoveConfig();
        if (level == 2 && userData.getBlessing() < config.getHighLevelUnlockBlessNum()) {
            return GameErrorCode.E_WINTER_LOVE_HIGH_LEVEL_NO_UNLOCK;
        }
        //取出消耗与积分奖励数量
        int consumeCount = level == 1 ? 1 : config.getHighLevelCost();
        String consumeString = config.getShovelItemId() + "=" + consumeCount;
        String rewardString = config.getScoreItemId() + "=";
        int rewardScoreNum = level == 1 ? WinterLoveMgr.getScoreReward() : WinterLoveMgr.getScoreReward() * config.getHighLevelScoreMultiple();         //高级场积分奖励乘一个倍数
        rewardString = rewardString + rewardScoreNum;

        List<Integer> mapData = level == 1 ? userData.getLowMapData() : userData.getHighMapData();      //取出雪地信息
        List<WinterLoveMapAnimal> mapAnimalList = level == 1 ? userData.getLowAnimalPosition() : userData.getHighAnimalPosition();        //取出操作场次的动物地图
        for (WinterLoveMapAnimal winterLoveMapAnimal : mapAnimalList) {
            if (winterLoveMapAnimal.getAnimalNum() == animalNum) {
                //扣除物品，不足返回
                if (!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(consumeString), eLogMoneyType.WinterLoveActivity, eLogMoneyType.WinterLoveActivity)) {
                    return GameErrorCode.E_WINTER_LOVE_SHOVEL_NO_ENOUGH;
                }

                List<Integer> dogEffectGrids = getGridsByDirection(winterLoveMapAnimal.getMainDogGrig() % 6, winterLoveMapAnimal.getMainDogGrig() / 6, 3);

                //赶狗成功
                mapAnimalList.remove(winterLoveMapAnimal);
                if (level == 1) {
                    userData.setLowAnimalPosition(mapAnimalList);
                } else {
                    userData.setHighAnimalPosition(mapAnimalList);
                }
                //加积分,变排行
                player.getModule(CurrencyModule.class).addCurrency(config.getScoreItemId() + "=" + rewardScoreNum, eLogMoneyType.WinterLoveActivity, eLogMoneyType.WinterLoveDigSnowReward);
                userData.setScore(userData.getScore() + rewardScoreNum);
                player.notifyListener(eGamePlayerEventType.WinterLoveRank.getValue(), userData.getScore());

                //日志记录
                int turnNum = level == 1 ? userData.getLowTurn() : userData.getHighTurn();
                LogWinterLoveDig logWinterLoveDig = new LogWinterLoveDig(player.getUserId(), config.getActivityInfo().getActivityId(),
                        level, turnNum, 1, new ArrayList<>(dogEffectGrids), userData.getScore() - rewardScoreNum, rewardScoreNum, userData.getScore(), new Date());
                LogMgr.addLogWinterLoveDig(logWinterLoveDig);
                userData.setUpdateOption();

                //发消息
                WinterLoveProto.KickAnimalRespMsg.Builder builder = WinterLoveProto.KickAnimalRespMsg.newBuilder();
                builder.setRet(0);
                builder.setKickAnimalNum(animalNum);
                builder.setScoreReward(rewardString);
                builder.setUserData(WinterLovePb.parseWinterLoveUserDataRespMsg(userData));
                player.sendPacket(Protocol.U_WINTER_LOVE_KICK_ANIMAL_RESULT, builder);
                return 0;
            }
        }
        return 1;
    }

    /**
     * 判断是否领取所有奖励，开启下一轮?
     */

    private boolean isNextTurn(WinterLoveUserData winterLoveUserData, int level) {
        List<WinterLoveMapItem> winterLoveMapItemList = level == 1 ? winterLoveUserData.getLowRewardMapData() : winterLoveUserData.getHighRewardMapData();
        for (WinterLoveMapItem winterLoveMapItem : winterLoveMapItemList) {
            if (winterLoveMapItem.getInBag() == 0 && !winterLoveMapItem.isBoxItem()){
                return false;
            }
        }
        return true;
    }

    /**
     * 切换场次
     */
    public int changelevel() {
        if (userData.getLevel() == 1 && userData.getBlessing() < WinterLoveMgr.getWinterLoveConfig().getHighLevelUnlockBlessNum()) {
            return GameErrorCode.E_WINTER_LOVE_HIGH_LEVEL_NO_UNLOCK;
        }
        if (userData.getLevel() == 1) {
            userData.setLevel(2);
        } else if (userData.getLevel() == 2) {
            userData.setLevel(1);
        }
        WinterLoveProto.changeLevelRespMsg.Builder respBuilder = WinterLoveProto.changeLevelRespMsg.newBuilder();
        WinterLoveProto.WinterLoveUserDataMsg.Builder builder = WinterLovePb.parseWinterLoveUserDataRespMsg(userData);
        respBuilder.setRet(0);
        respBuilder.setUserdata(builder);
        player.sendPacket(ClientProtocol.U_WINTER_LOVE_CHANGE_LEVEL_RESULT, respBuilder);
        return 0;
    }

    /**
     * 生成地图上的动物
     */
    private void generateDog(WinterLoveUserData winterLoveUserData, int level) {
        Random random = new Random();
        //取出当前场次动物列表
        List<WinterLoveMapAnimal> animalList = level == 1 ? winterLoveUserData.getLowAnimalPosition() : winterLoveUserData.getHighAnimalPosition();
        WinterLoveConfig config = WinterLoveMgr.getWinterLoveConfig();
        List<Integer> dogGridList = new ArrayList<>();
        for (int i = 0, num = 0; i < 1000; i++) {
            int randomX = random.nextInt(5);
            int randomY = random.nextInt(5);
            //动物从5*5的格子中随机，取右下角也就是方向3的四个格子
            List<Integer> randomGrids = getGridsByDirection(randomX, randomY, 3);
            randomGrids.removeAll(dogGridList);                 //去掉其他动物占用
            if (randomGrids.size() == 4) {
                WinterLoveMapAnimal winterLoveMapAnimal = new WinterLoveMapAnimal();
                winterLoveMapAnimal.setAnimalNum(num);
                num++;
                winterLoveMapAnimal.setAnimalType(random.nextInt(3));
                winterLoveMapAnimal.setMainDogGrig(getGridsByDirection(randomX, randomY, 0).get(0));
                dogGridList.addAll(randomGrids);
                animalList.add(winterLoveMapAnimal);
            } else {
                continue;
            }
            //如果生成满了
            if (dogGridList.size() >= 4 * config.getMapAnimalNum()) {
                break;
            }
        }
    }

    /**
     * 生成一下各个场次奖励
     */
    private void generateReward(WinterLoveUserData winterLoveUserData, int level) {
        Random random = new Random();
        WinterLoveConfig config = WinterLoveMgr.getWinterLoveConfig();
        List<Integer> rewardGridList = new ArrayList<>();
        List<WinterLoveMapItem> mapItemList = new ArrayList<>();

        //取出物品与权重表
        List<WinterLoveItem> itemList = level == 1 ? config.getWinterLoveLowItemList() : config.getWinterLoveHighItemList();
        List<Integer> weightList = level == 1 ? config.getWinterLoveLowWeightList() : config.getWinterLoveHighWeightList();
        WinterLoveItem boxItem = WinterLoveMgr.getBoxItem(level);
        //取出当前场次物品列表
        if (level == 1) {
            mapItemList = winterLoveUserData.getLowRewardMapData();
        } else {
            mapItemList = winterLoveUserData.getHighRewardMapData();
        }
        int boxGridNum = random.nextInt(36);
        List<Integer> boxOccupyList = new ArrayList<>();
        boxOccupyList.add(boxGridNum);
        WinterLoveMapItem winterLoveMapBox = new WinterLoveMapItem(0, boxItem.getItemId(), boxOccupyList, 0, 0, true);
        mapItemList.add(winterLoveMapBox);
        rewardGridList.add(boxGridNum);

        List<WinterLoveItem> winterLoveItemList = generateItemThisTurn(itemList, weightList, config.getMapMaxFullRate());
        winterLoveItemList.sort(new Comparator<WinterLoveItem>() {
            @Override
            public int compare(WinterLoveItem o1, WinterLoveItem o2) {
                return o1.getType() - o2.getType();
            }
        }.reversed());
        int itemNum = 1;
        for (WinterLoveItem winterLoveItem : winterLoveItemList) {
            for (int i = 0; i < 1000; i++) {
                int randomX = random.nextInt(6);
                int randomY = random.nextInt(6);
                if (rewardGridList.contains(getGridsByDirection(randomX, randomY, 0).get(0))) {
                    continue;
                }
                List<Integer> randomFreeGrid = getMaxContainDirection(randomX, randomY, rewardGridList);
                int randomDirection = 0;
                if (winterLoveItem.getType() == 4) {
                    randomDirection = random.nextInt(3);
                } else {
                    randomDirection = random.nextInt(2);
                }
                if (randomFreeGrid.size() == winterLoveItem.getType()) {
                    WinterLoveMapItem winterLoveMapItem = new WinterLoveMapItem(itemNum, winterLoveItem.getItemId(), randomFreeGrid, randomDirection, 0, false);
                    //有两个不能旋转
                    if (winterLoveItem.getItemId()==10005||winterLoveItem.getItemId()==10012){
                        winterLoveMapItem.setRotation(0);
                    }
                    mapItemList.add(winterLoveMapItem);
                    rewardGridList.addAll(randomFreeGrid);
                    itemNum++;
                    break;
                } else if (randomFreeGrid.size() == 4 && randomFreeGrid.size() > winterLoveItem.getType()) {          //四格位置生成两格
                    List<Integer> realOccupyList = getRandomTwoGrid(randomFreeGrid, random);
                    WinterLoveMapItem winterLoveMapItem = new WinterLoveMapItem(itemNum, winterLoveItem.getItemId(), realOccupyList, randomDirection, 0, false);
                    mapItemList.add(winterLoveMapItem);
                    rewardGridList.addAll(realOccupyList);
                    itemNum++;
                    break;
                } else {
                    continue;
                }
            }
        }
        if (level == 1) {
            winterLoveUserData.setLowRewardMapData(mapItemList);
        } else {
            winterLoveUserData.setHighRewardMapData(mapItemList);
        }

    }


    /**
     * 随机礼物出来
     */
    List<WinterLoveItem> generateItemThisTurn(List<WinterLoveItem> itemList, List<Integer> weightList, int maxRate) {
        Map<Integer, Integer> hasGeneratedRewardMap = new ConcurrentHashMap<>();
        List<WinterLoveItem> mapItemList = new ArrayList<>();
        for (WinterLoveItem winterLoveItem : itemList) {
            hasGeneratedRewardMap.put(winterLoveItem.getItemId(), 0);
        }
        int occupyGridNum = 0;

        for (int i = 0, num = 0; i < 1000; i++) {
            int itemIndex = RandomHelper.getRandomIndexByWeight(weightList);
            WinterLoveItem itemConfig = itemList.get(itemIndex);
            if (hasGeneratedRewardMap.get(itemConfig.getItemId()) >= itemConfig.getMaxNum()) {
                continue;
            }
            mapItemList.add(itemConfig);
            occupyGridNum += itemConfig.getType();
            int oldNum = hasGeneratedRewardMap.get(itemConfig.getItemId());
            hasGeneratedRewardMap.put(itemConfig.getItemId(),oldNum+1);
            if (occupyGridNum >= maxRate - 1) {
                break;
            }
        }
        return mapItemList;
    }

    /**
     *四格随机两格方法
     */
    private List<Integer> getRandomTwoGrid(List<Integer> list, Random random) {
        List<Integer> twoGridList = new ArrayList<>();
        int randomTwoGrid = random.nextInt(4);
        if (randomTwoGrid == 0) {
            twoGridList.add(list.get(0));
            twoGridList.add(list.get(1));
        } else if (randomTwoGrid == 1) {
            twoGridList.add(list.get(1));
            twoGridList.add(list.get(2));
        } else if (randomTwoGrid == 2) {
            twoGridList.add(list.get(2));
            twoGridList.add(list.get(3));
        } else if (randomTwoGrid == 3) {
            twoGridList.add(list.get(3));
            twoGridList.add(list.get(0));
        }
        return twoGridList;
    }


    /**
     * 使用点坐标来寻找出四周可以塞最多的的空闲格子
     */
    private List<Integer> getMaxContainDirection(int X, int Y, List<Integer> rewardGridList) {
        //取出四个方向的合法格子
        List<Integer> maxContainList = new ArrayList<>();
        List<Integer> surroundList1 = getGridsByDirection(X, Y, 1);
        List<Integer> surroundList2 = getGridsByDirection(X, Y, 2);
        List<Integer> surroundList3 = getGridsByDirection(X, Y, 3);
        List<Integer> surroundList4 = getGridsByDirection(X, Y, 4);
        //四个方向合法格子去除已经被礼物占据的格子,去除放不了两格的格子
        selectGridFitReward(surroundList1, rewardGridList);
        selectGridFitReward(surroundList2, rewardGridList);
        selectGridFitReward(surroundList3, rewardGridList);
        selectGridFitReward(surroundList4, rewardGridList);
        List<List<Integer>> allList = new ArrayList<>();
        //算出最多格子的数量
        int maxCount = 0;
        int maxGridNum = Math.max(surroundList1.size(), surroundList2.size());
        maxGridNum = Math.max(maxGridNum, surroundList3.size());
        maxGridNum = Math.max(maxGridNum, surroundList4.size());

        if (surroundList1.size() == maxGridNum) {
            allList.add(surroundList1);
            maxCount++;
        }
        if (surroundList2.size() == maxGridNum) {
            allList.add(surroundList2);
            maxCount++;
        }
        if (surroundList3.size() == maxGridNum) {
            allList.add(surroundList3);
            maxCount++;
        }
        if (surroundList4.size() == maxGridNum) {
            allList.add(surroundList4);
            maxCount++;
        }
        if (maxCount == 1) {
            maxContainList.addAll(allList.get(0));
            return maxContainList;
        } else {            //多于一个方向可以容纳相同格子装饰物则随机一个返回
            Random random = new Random();
            int randomNum = random.nextInt(maxCount);
            maxContainList.addAll(allList.get(randomNum));
            return maxContainList;
        }
    }

    /**
     * 传入随机点周围格子的列表，去除无法使用以及对角格子，返回可以使用的格子数组
     */
    private void selectGridFitReward(List<Integer> originalList, List<Integer> rewardGridList) {
        Random random = new Random();
        originalList.removeAll(rewardGridList);
        //两格斜对角,放不了两格
        if (originalList.size() == 2) {
            if ((Math.abs(originalList.get(0) - originalList.get(1)) == 7) || (Math.abs(originalList.get(0) - originalList.get(1)) == 5)) {
                originalList.remove(random.nextInt(2));
                return;
            }
        }
        //空闲格子如果是三格，把多的一格去掉
        if (originalList.size() == 3) {
            for (int i = 1; i < 3; i++) {
                if (Math.abs(originalList.get(0) - originalList.get(i)) == 7 || Math.abs(originalList.get(0) - originalList.get(i)) == 5) {
                    int randomDelete = random.nextInt(2);
                    if (randomDelete == 1) {
                        originalList.remove(i);
                    } else {
                        originalList.remove(0);
                    }
                    return;
                }
            }
            return;
        }
        //空闲格子如果是2格对角，去掉一格
        if (originalList.size() == 2) {
            if (originalList.get(0) - originalList.get(1) == 7 || Math.abs(originalList.get(0) - originalList.get(1)) == 5) {
                originalList.remove(random.nextInt(2));
            }
        }
    }

    /**
     * 通过格子 X,Y 坐标判断是否存在，大于5的不存在
     */

    private static boolean checkGridExist(int x, int y) {
        return x >= 0 && y >= 0 && x <= 5 && y <= 5;
    }

    /**
     * 通过点的坐标来找出某个方向的点,0为取自身,1为拿格子左上,2为拿格子右上,3为格子右下,4为格子左下。同1234象限
     */
    private List<Integer> getGridsByDirection(int x, int y, int direction) {
        List<Integer> gridList = new ArrayList<>();
        if (direction == 0) {
            gridList.add(y * 6 + x);
            return gridList;
        }
        if (direction == 1) {
            if (checkGridExist(x - 1, y - 1)) {
                gridList.add((y - 1) * 6 + (x - 1));
            }
            if (checkGridExist(x, y - 1)) {
                gridList.add((y - 1) * 6 + (x));
            }
            gridList.add(y * 6 + x);
            if (checkGridExist(x - 1, y)) {
                gridList.add((y) * 6 + (x - 1));
            }
            return gridList;
        }
        if (direction == 2) {
            if (checkGridExist(x, y - 1)) {
                gridList.add((y - 1) * 6 + (x));
            }
            if (checkGridExist(x + 1, y - 1)) {
                gridList.add((y - 1) * 6 + (x + 1));
            }
            if (checkGridExist(x + 1, y)) {
                gridList.add((y) * 6 + (x + 1));
            }
            gridList.add((y) * 6 + (x));
            return gridList;
        }
        if (direction == 3) {
            gridList.add((y) * 6 + (x));
            if (checkGridExist(x + 1, y)) {
                gridList.add((y) * 6 + (x + 1));
            }
            if (checkGridExist(x + 1, y + 1)) {
                gridList.add((y + 1) * 6 + (x + 1));
            }
            if (checkGridExist(x, y + 1)) {
                gridList.add((y + 1) * 6 + (x));
            }
            return gridList;
        }
        if (direction == 4) {
            if (checkGridExist(x - 1, y)) {
                gridList.add((y) * 6 + (x - 1));
            }
            gridList.add((y) * 6 + (x));
            if (checkGridExist(x, y + 1)) {
                gridList.add((y + 1) * 6 + (x));
            }
            if (checkGridExist(x - 1, y + 1)) {
                gridList.add((y + 1) * 6 + (x - 1));
            }
            return gridList;
        }
        return gridList;
    }

    /**
     * 同步冬季恋歌用户数据
     */
    public void syncUserData() {
        if (this.userData == null) {
            return;
        }
        syncPlayerData();
    }

    private void syncPlayerData() {
        if (this.userData == null) {
            return;
        }
        if (null == WinterLoveMgr.getActivityInfo()) {
            return;
        }
        WinterLoveProto.WinterLoveUserDataMsg.Builder syncBuilder = WinterLovePb.parseWinterLoveUserDataRespMsg(userData);
        player.sendPacket(ClientProtocol.U_WINTER_LOVE_SEND_USER_DATA, syncBuilder);
    }

    /**
     * 同步冬季恋歌配置数据
     */
    public void syncWinterLoveConfig() {
        WinterLoveConfig winterLoveConfig = WinterLoveMgr.getWinterLoveConfig();
        if (winterLoveConfig != null && ActivityMgr.activityInShowTime(winterLoveConfig.getActivityInfo())) {
            WinterLoveProto.CombConfigMsg.Builder combBuilder = WinterLovePb.parseWinterLoveCombConfigRespMsg(winterLoveConfig, player.getLanguage());
            WinterLoveProto.ItemConfigMsg.Builder itemBuilder = WinterLovePb.parseWinterLoveItemConfigRespMsg(winterLoveConfig, player.getLanguage());
            player.sendPacket(ClientProtocol.U_WINTER_LOVE_SYNC_ITEM_CONFIG, itemBuilder);
            player.sendPacket(ClientProtocol.U_WINTER_LOVE_SYNC_COMB_CONFIG, combBuilder);
        }
    }

    /**
     * 初始化用户数据
     */
    public synchronized void initUserData() {
        WinterLoveConfig winterLoveConfig = WinterLoveMgr.getWinterLoveConfig();
        //未解锁
        if (!SystemOpenMgr.systemOpen(player, eSystemId.WinterLoveActivity.getValue())) {
            return;
        }
        //无活动
        ActivityInfo activityInfo = WinterLoveMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }
        if (null == userData || (userData.getActivityId() != activityInfo.getActivityId())) {
            WinterLoveUserData tmpUserData = new WinterLoveUserData();
            tmpUserData.setActivityId(activityInfo.getActivityId());
            tmpUserData.setUserId(player.getUserId());
            tmpUserData.setLevel(1);
            tmpUserData.setBlessing(0);
            tmpUserData.setLowTurn(0);
            tmpUserData.setHighTurn(0);
            //用户信息内加入配置中所有的道具信息，数量为0
            tmpUserData.setDecoration(new ArrayList<>());
            List<WinterLoveItem> winterLoveItemList = new ArrayList<>(winterLoveConfig.getWinterLoveLowItemList());
            winterLoveItemList.addAll(winterLoveConfig.getWinterLoveHighItemList());
            for (WinterLoveItem winterLoveItem : winterLoveItemList) {
                tmpUserData.getDecoration().add(new WinterLoveBagItem(winterLoveItem.getItemId(), 0));
            }
            //随机美女
            tmpUserData.setBeautyId(WinterLoveMgr.getRandomBeautyId());
            tmpUserData.setScore(0);
            //生成高低级场次的装饰物，宝箱和动物
            tmpUserData.setLowRewardMapData(new ArrayList<>());
            tmpUserData.setLowAnimalPosition(new ArrayList<>());
            tmpUserData.setHighRewardMapData(new ArrayList<>());
            tmpUserData.setHighAnimalPosition(new ArrayList<>());

            generateReward(tmpUserData, 1);
            generateReward(tmpUserData, 2);
            generateDog(tmpUserData, 1);
            generateDog(tmpUserData, 2);
            //生成一块全新雪地
            List<Integer> lowMapData = new ArrayList<>();
            List<Integer> highMapData = new ArrayList<>();
            for (int i = 0; i < 36; i++) {
                lowMapData.add(0);
                highMapData.add(0);
            }
            tmpUserData.setLowMapData(lowMapData);
            tmpUserData.setHighMapData(highMapData);
            tmpUserData.setDisperseTimes(0);
            tmpUserData.setInsertOption();

            userData = tmpUserData;
        }

    }

    /**
     * 系统解锁
     */
    public void initSystem() {
        if (null == userData) {
            initUserData();
        }
    }

    public WinterLoveUserData getUserData() {
        return userData;
    }

}
